package dao;

import bean.Department;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;
import java.util.List;

public class DepartmentDAOImpl implements DepartmentDAO {
    private Session session;
    private Transaction transaction;
    private boolean completed;

    public DepartmentDAOImpl(Session session) {
        this.session = session;
    }

    @Override
    public boolean add(Department department) {
        try {
            transaction = session.beginTransaction();
            session.save(department);
            completed = true;
        } catch (Exception e) {
            completed = false;
            e.printStackTrace();
        } finally {
            transaction.commit();
        }
        return completed;
    }

    @Override
    public boolean edit(Department temporary) {
        try {
            transaction = session.beginTransaction();
            Department department = session.get(Department.class, temporary.getDepartmentId());
            department.setDepartmentName(temporary.getDepartmentName());
            session.save(department);
            completed = true;
        } catch (Exception e) {
            completed = false;
            e.printStackTrace();
        } finally {
            transaction.commit();
        }
        return completed;
    }

    @Override
    public boolean remove(int departmentId) {
        try {
            transaction = session.beginTransaction();
            Department department = session.get(Department.class, departmentId);
            session.delete(department);
            completed = true;
        } catch (Exception e) {
            completed = false;
            e.printStackTrace();
        } finally {
            transaction.commit();
        }
        return completed;
    }

    @Override
    public List<Department> queryAll() {
        List<Department> departments = null;
        try {
            @SuppressWarnings("unchecked")
            Query<Department> query = session.createQuery("FROM Department");
            departments = query.list();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return departments;
    }

    @Override
    public Department query(int departmentId) {
        Department department = null;
        try {
            @SuppressWarnings("unchecked")
            Query<Department> query = session.createQuery("FROM Department WHERE departmentId=" + departmentId);
            department = query.list().get(0);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return department;
    }
}
